package cn.ktp.auth.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import com.alibaba.fescar.rm.datasource.DataSourceProxy;
import com.alibaba.fescar.spring.annotation.GlobalTransactionScanner;

/**
 * @Author: kris
 * @Description  fescar全局设置，对数据源进行增强
 * @Date Created in 2019/1/24 10:28
 */
@Configuration
@Import(DruidDataSourceAutoConfigure.class)
public class FescarConfig {

    /**
     * 包装数据源代理，用于在执行SQL之前生成回退日志
     * @Param: druidDataSource  datasource bean instance
     * @Return: DataSourceProxy  datasource proxy
     */
    @Bean
    public DataSourceProxy dataSourceProxy(DataSource druidDataSource){
        return new DataSourceProxy((DruidDataSource)druidDataSource);
    }

    /**
     * 替换 mybatis 的sqlSessionFactory，用数据源代理替换自动装配的数据源
     * @Param: dataSourceProxy  fescar数据源代理
     * @Return: SqlSessionFactory  mybatic使用的数据源
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSourceProxy dataSourceProxy) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSourceProxy);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:/mapper/*.xml"));
        factoryBean.setTransactionFactory(new JdbcTransactionFactory());
        return factoryBean.getObject();
    }


    /**
     * 初始化全局事务扫描器
     *
     * @Return: GlobalTransactionScanner
     */
    @Bean
    public GlobalTransactionScanner globalTransactionScanner(){
        return new GlobalTransactionScanner("auth_service", "my_test_tx_group");
    }
}

